import type {
  ProjectConfig,
  HeaderSetting,
  AppInfo,
  MenuSetting,
  MultiTabsSetting
} from '#/config';

import { defineStore } from 'pinia';
import { store } from '@/store';
import projectConfig from '@/settings/project-setting';
import { resetRouter } from '@/router';
import { deepMerge } from '@/utils';
import { appInfo } from '@/config/app-info';
import { getAppEnvConfig } from '@/utils/env';

const { VITE_APP_ID } = getAppEnvConfig();
interface AppState {
  // Page loading status
  pageLoading: boolean;
  // project config
  projectConfig: ProjectConfig;
  appInfo: AppInfo;
}
let timeId: TimeoutHandle;
export const useAppStore = defineStore({
  id: 'app',
  state: (): AppState => ({
    pageLoading: false,
    projectConfig: deepMerge({}, projectConfig),
    appInfo: {
      ...appInfo,
      appId: VITE_APP_ID
    }
  }),
  getters: {
    getPageLoading(state): boolean {
      return state.pageLoading;
    },

    getProjectConfig(state): ProjectConfig {
      return (state.projectConfig || projectConfig) as ProjectConfig;
    },

    getHeaderSetting(): HeaderSetting {
      return this.getProjectConfig.headerSetting;
    },
    getMenuSetting(): MenuSetting {
      return this.getProjectConfig.menuSetting;
    },
    getMultiTabsSetting(): MultiTabsSetting {
      return this.getProjectConfig.multiTabsSetting;
    },
    getAppId(state) {
      return state.appInfo.appId;
    }
  },
  actions: {
    setPageLoading(loading: boolean): void {
      this.pageLoading = loading;
    },

    setProjectConfig(config: DeepPartial<ProjectConfig>): void {
      this.projectConfig = deepMerge(this.projectConfig || {}, config) as ProjectConfig;
    },
    setMenuSetting(setting: MenuSetting) {
      this.projectConfig!.menuSetting = deepMerge(
        this.projectConfig!.menuSetting,
        setting
      ) as MenuSetting;
    },

    async resetAllState() {
      resetRouter();
    },
    async setPageLoadingAction(loading: boolean): Promise<void> {
      if (loading) {
        clearTimeout(timeId);
        // Prevent flicker
        timeId = setTimeout(() => {
          this.setPageLoading(loading);
        }, 50);
      } else {
        this.setPageLoading(loading);
        clearTimeout(timeId);
      }
    }
  }
});

// Need to be used outside the setup
export function useAppStoreWithOut() {
  return useAppStore(store);
}
